package com.zzyl.nursing.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 * 
 * @author Nuyoah
 * @date 2025-05-17
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private IBedService bedService;
    @Autowired
    private IElderService elderService;
    @Autowired
    private IContractService contractService;
    @Autowired
    private ICheckInConfigService checkInConfigService;

    /**
     * 申请入住
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        //1.校验老人是否已入住
        //1.1获取老人身份证号
        String idCardNo = dto.getCheckInElderDto().getIdCardNo();
        Long count = this.lambdaQuery().eq(CheckIn::getIdCardNo, idCardNo).eq(CheckIn::getStatus, 0).count();
        if (count>0){
            throw new RuntimeException("老人已入住过");
        }

        //2. 判断符合要求的床位是否已存在 select * from bed where id=? and bed_status=0
        Long bedId = dto.getCheckInConfigDto().getBedId();
        Bed bed = bedService.lambdaQuery().eq(Bed::getBedStatus, 0).eq(Bed::getId, bedId).one();
        if (bed == null){
            throw new RuntimeException("暂无符合床位");
        }

        //3.更为床位状态为已入住
        boolean bedResult = bedService.lambdaUpdate().eq(Bed::getId, bedId)
                .set(Bed::getBedStatus, 1).update();
        if (!bedResult){
            throw new RuntimeException("更新床位状态失败");
        }

        //4.新增或更新老人
        //查询老人信息 select * from elder where id_card_no=?
        Elder elder = getElder(dto, idCardNo, bedId, bed);

        //5.新增签约办理
        getContract(dto, elder);

        //6.新增入住信息
        CheckIn checkIn = getCheckIn(dto, elder, bed);

        //7.新增入住配置
        getCheckInConfig(dto, checkIn);
    }

    /**
     *新增入住配置
     * @param dto
     * @param checkIn
     */
    private void getCheckInConfig(CheckInApplyDto dto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());//设置入住id
        boolean checkInConfigResult = checkInConfigService.save(checkInConfig);
        if (!checkInConfigResult){
            throw new RuntimeException("新增入住配置信息失败");
        }
    }

    /**
     * 新增入住信息
     * @param dto
     * @param elder
     * @param bed
     * @return
     */
    @NotNull
    private CheckIn getCheckIn(CheckInApplyDto dto, Elder elder, Bed bed) {
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkIn);
        checkIn.setElderName(elder.getName());//获取入住老人姓名
        checkIn.setElderId(elder.getId());//获取入住老人id
        checkIn.setIdCardNo(elder.getIdCardNo());//获取入住老人身份证号
        checkIn.setBedNumber(bed.getBedNumber());//获取入住床位编号
        checkIn.setStatus(0);
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));//获取前端传过来的加属性信息以json字符串的方式存入入住信息的备注中
        boolean checkInResult = this.save(checkIn);
        if (!checkInResult) {
            throw new RuntimeException("新增入住信息失败");
        }
        return checkIn;
    }

    /**
     * 新增签约办理
     * @param dto
     * @param elder
     */
    private void getContract(CheckInApplyDto dto, Elder elder) {
        Contract contract = new Contract();//创建合同对象
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);//拷贝合同基本信息
        contract.setElderId(elder.getId());//设置老人id
        contract.setContractNumber("HT"+CodeGenerator.generateContractNumber());//设置合同编号
        contract.setElderName(elder.getName());//设置老人姓名
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());//设置合同开始时间
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());//设置合同结束时间
        //判断合同的状态
        int status = LocalDateTime.now().isBefore(contract.getStartDate()) ? 0 : LocalDateTime.now().isBefore(contract.getEndDate()) ? 1 : 2;
        contract.setStatus(status);//设置合同状态
        boolean contractResult = contractService.save(contract);
        if (!contractResult){
            throw new RuntimeException("新增签约办理失败");
        }
    }

    /**
     * 新增或更新老人
     * @param dto
     * @param idCardNo
     * @param bedId
     * @param bed
     * @return
     */
    @NotNull
    private Elder getElder(CheckInApplyDto dto, String idCardNo, Long bedId, Bed bed) {
        Elder elder = elderService.lambdaQuery().eq(Elder::getIdCardNo, idCardNo).one();//查询老人的信息
        if(elder==null){
            elder = new Elder();
        }
        BeanUtils.copyProperties(dto.getCheckInElderDto(), elder);
        elder.setStatus(4);//设置老人状态为入住中
        elder.setBedId(bedId);//设置床位id
        elder.setBedNumber(bed.getBedNumber());//设置床位编号
        boolean saveResult = elderService.save(elder);
        if (!saveResult){
            throw new RuntimeException("新增或更新老人信息失败");
        }
        return elder;
    }

    /**
     * 获取入住详细信息
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo getDetail(Long id) {
        //1.根据id查询入住信息
        CheckIn checkIn = this.lambdaQuery().eq(CheckIn::getId, id).one();
        if (checkIn==null){
            throw new RuntimeException("入住信息不存在");
        }
        //2.查询老人信息
        Elder elder = elderService.lambdaQuery().eq(Elder::getId, checkIn.getElderId()).one();
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        checkInElderVo.setAge(DateUtil.ageOfNow(elder.getBirthday()));

        //3.查询合同信息
        Contract contract = contractService.lambdaQuery().eq(Contract::getElderId, elder.getId()).one();
        Contract contractVo = new Contract();
        BeanUtils.copyProperties(contract, contractVo);

        //4.查询入住配置
        CheckInConfig checkInConfig = checkInConfigService.lambdaQuery().eq(CheckInConfig::getCheckInId, checkIn.getId()).one();
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());


        //5.将入住信息中的remark属性值转换为家属列表
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);

        //6.整合数据返回
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo(checkInElderVo,  elderFamilyVoList, checkInConfigVo, contractVo);
        return checkInDetailVo;
    }
}
